package cn.itcast.system.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.system.service.PermissionService;
import cn.itcast.system.service.RoleService;
import cn.itcast.system.service.UserService;

//@Service("bosRealm")
public class BosRelam extends AuthorizingRealm {

	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permissionService;
	@Override
	//授权
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("授权中...");
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//根据当前用户查询权限和角色
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getPrincipal();
		//角色
		List<Role> roles = roleService.findByUser(user);
		for (Role role : roles) {
			authorizationInfo.addRole(role.getKeyword());
			
			
		}
		//权限
		List<Permission> promissions = permissionService.findByUser(user);
		for (Permission permission : promissions) {
			authorizationInfo.addStringPermission(permission.getKeyword());
			
			
		}
		return authorizationInfo;
	}

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("认证中.....");
		UsernamePasswordToken usernamePasswordToken=(UsernamePasswordToken) token;
		//通过用户名查询用户
		User user = userService.findByUsername(usernamePasswordToken.getUsername());
		//判断用户是否存在
		if (user == null) {
			//用户不存在
			return null;
		} else {
			//用户存在
			//自动校验密码
			return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
		}
	}

}
